﻿namespace Digitalmes.Application.Sys.Dicts.Commands;

/// <summary>
/// 创建字典数据项命令。
/// </summary>
/// <param name="DictData"></param>
public record CreateDictItemCommand(SysDictItemDto DictData) : IRequest<IResult<bool>>;

internal sealed class CreateDictItemCommandHandler(IRepository<SysDictItem> repo) : IRequestHandler<CreateDictItemCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CreateDictItemCommand request, CancellationToken cancellationToken)
    {
        // 检查字典是否已存在。
        if (await repo.IsAnyAsync(m => m.Label == request.DictData.Label && m.DictId == request.DictData.DictId, cancellationToken))
        {
            return Result.Failure("字典项标签已存在");
        }

        var dict = request.DictData.Adapt<SysDictItem>();
        var ok = await repo.InsertAsync(dict, cancellationToken);
        return Result.From(ok);
    }
}
